﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Facebook;
using Facebook.Properties;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using Entities;
using System.IO;

namespace PictureOrganizer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string _url = String.Empty;
        private string _json = String.Empty;
        private Album _currentAlbum;
        private List<Album> _albums;
        private List<Photo> _photos;
        private Photo _currentPhoto;
        private Entities.Image _currentImage;
        private List<Entities.Image> _images;

        private string _pathSeperator = System.IO.Path.DirectorySeparatorChar.ToString();
        private string _pathApplication = Environment.CurrentDirectory;

        private string _accesstoken = String.Empty; 

        //URL
        private string _urlGetPhotosFromAlbum = "https://api.facebook.com/method/photos.get?format=json&access_token={0}&aid={1}";
        private string _urlGetAlbums = "https://api.facebook.com/method/photos.getAlbums?format=json&access_token={0}";

        private enum enumImageSize { small = 0, medium = 1, large = 2 };

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnGetAlbums_Click(object sender, RoutedEventArgs e)
        {
            ResetResults();

            GetAlbums();
        }

        private void GetAlbums()
        {
            _accesstoken = txtToken.Text;

            string json = GetJSON(String.Format(_urlGetAlbums, _accesstoken));
            _albums = ConvertJsonToAlbum(json);

            foreach (Album album in _albums)
            {
                lstResult.Items.Add(album);
            }
        }

        private void GetPhotosFromAlbum()
        {
            if (_currentAlbum != null)
            {
                string json = GetJSON(String.Format(_urlGetPhotosFromAlbum, _accesstoken, _currentAlbum.aid));
                _photos = ConvertJsonToPhotos(json);

                _currentAlbum.Photos = _photos;

                foreach (Photo photo in _photos)
                {
                    lstResult.Items.Add(photo);
                }
            }
        }

        private List<Photo> ConvertJsonToPhotos(string json)
        {
            List<Photo> _photos = JsonConvert.DeserializeObject<List<Photo>>(json);

            return _photos;
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            ResetResults();
        }

        private void lstResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _currentAlbum = (Album)lstResult.SelectedItem;
            GetPhotosFromAlbum();
        }

        private void ShowResults()
        {

        }

        private List<Album> ConvertJsonToAlbum(string json)
        {
            List<Album> _albums = JsonConvert.DeserializeObject<List<Album>>(json);

            return _albums;
        }

        private string GetJSON(string url)
        {
            string json = String.Empty;

            using (var webClient = new System.Net.WebClient())
            {
                json = webClient.DownloadString(url);
            }

            return json;
        }

        private void ResetResults()
        {
            _url = String.Empty;
            _json = String.Empty;

            _currentAlbum = new Album();
            _albums = new List<Album>();
            _photos = new List<Photo>();
            _currentPhoto = new Photo();
            _currentImage = new Entities.Image();
            _images = new List<Entities.Image>();

            lstResult.Items.Clear();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ResetResults();
        }

        private void btnGetPhotos_Click(object sender, RoutedEventArgs e)
        {
            DownloadPhotos();
        }

        private void CreateFolder(string folder)
        {
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
        }

        private void DownloadPhotos()
        {
            if (_currentAlbum != null && _photos != null)
            {
                string folderSmall = _pathApplication + _pathSeperator + _currentAlbum.name + _pathSeperator + enumImageSize.small.ToString() + "\\";
                string folderMedium = _pathApplication + _pathSeperator + _currentAlbum.name + _pathSeperator + enumImageSize.medium.ToString() + "\\";
                string folderLarge = _pathApplication + _pathSeperator + _currentAlbum.name + _pathSeperator + enumImageSize.large.ToString() + "\\";

                CreateFolder(folderSmall);
                CreateFolder(folderMedium);
                CreateFolder(folderLarge);

                foreach (Photo photo in _photos)
                {
                    DownloadPhotoFromURL(photo, folderSmall, enumImageSize.small);
                    DownloadPhotoFromURL(photo, folderMedium, enumImageSize.medium);
                    DownloadPhotoFromURL(photo, folderLarge, enumImageSize.large);
                }
            }
        }

        private void DownloadPhotoFromURL(Photo photo, string folder, enumImageSize size)
        {
            string source = String.Empty;

            switch(size) 
            {
                case enumImageSize.small:
                    source = photo.src_small;
                    break;
                case enumImageSize.medium:
                    source = photo.src;
                    break;
                case enumImageSize.large:
                    source = photo.src_big;
                    break;
            }

            using (var webClient = new System.Net.WebClient())
            {
                string extension = System.IO.Path.GetExtension(source);
                string saveFileTo = folder + photo.pid + extension;

                webClient.DownloadFile(source, saveFileTo);
            }
        }
    }
}